const { app, BrowserWindow,globalShortcut,ipcMain} = require('electron/main')
const path = require('node:path')
const SocketNioClient = require("./src/tools/SocketNioClient");
const {initTray,initSocketNioClient} =require( './src/print')
const { machineIdSync } = require("node-machine-id");
const {fileObj}=require('./src/tools/file')
const {address} = require("address");

global.sio = SocketNioClient();
global.machineId = machineIdSync({ original: true });
global.addressArg = null;
address(function(err, arg) {
  global.addressArg = arg;
});
global.MAIN_WINDOW = null;
global.APP_TRAY = null;
function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      devTools:true,
      contextIsolation:false,
      nodeIntegration: true,
      enableRemoteModule: true,
    }
  })
  win.loadFile('index.html')
  return win
}
app.whenReady().then(async () => {
  MAIN_WINDOW=createWindow();
  // 支持快捷键打开控制台
  globalShortcut.register('CommandOrControl+Shift+i', function () {
    MAIN_WINDOW.webContents.openDevTools();
  })
  initTray();// 定义应用最小化的时候托盘的样式和右击方法
  fileObj.init()
  let host = await fileObj.getConfigItem("host");
  let port = await fileObj.getConfigItem("port");
  if (host != "" && port != "" && host != null && port != null) {
     initSocketNioClient();
    // getHiprintTemplate();
    // initPrintEvent();
  }
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})
// 获取设备唯一id
ipcMain.on("getMachineId", function(event) {
  event.sender.send(
    "machineId",
    (global.machineId = machineIdSync({ original: true }))
  );
});
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})